<template>
  <div class="container">
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />
    <van-search
      show-action
      placeholder="请输入搜索关键词"
      shape="round"
      v-model.trim="keyword"
      @input="useGetSuggestion"
    >
      <div slot="action" @click="onSearch">搜索</div>
    </van-search>
    <!-- 联想建议 -->
    <van-cell-group v-if="keyword" key="sug-work">
      <van-cell
        v-for="(item, index) in lightSuggestion"
        :key="index"
        @click="suggestionSearch(index)"
        icon="search"
      >
        <div v-html="item"></div>
      </van-cell>
      <!-- <van-cell title="jsa" icon="search" /> -->
    </van-cell-group>
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <van-cell-group v-else key="sug-work">
      <van-cell v-if="histroys.length > 0" title="历史记录"> </van-cell>
      <!-- @click="$router.push({
                'path':'/search/result',
                'query':{
                    'keyword':item
                }
            })" -->
      <van-cell
        v-for="(item, index) in histroys"
        :key="index"
        :title="item"
        @click="$router.push(`/search/result?keyword=${item}`)"
      >
        <van-icon name="close" @click="dHistory(index)" />
      </van-cell>
    </van-cell-group>
    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
import { getSuggestion } from "@/api/search.js";
import { setItem, getItem } from "@/utils/localStorage.js";
const LOCALSTROAGE_SEARCH_NAME = "searchHistory";
export default {
  name: "video-index",
  data() {
    return {
      keyword: "",
      suggestions: [],
      timer: null,
      histroys: getItem(LOCALSTROAGE_SEARCH_NAME) || [] // 保存历史记录
    };
  },
  computed: {
    lightSuggestion() {
      /**
       * map [122,323423,4234,]
       */
      return this.suggestions.map(str => {
        // str 就是我们数组里面的每一个内容
        /**
               *正则表达式  1 动态创建匹配规则 new RegExp(this.keyword,'gi')
                           2. replace(,()=>{})
                           3. return;
                           str=> str
               */
        const reg = new RegExp(this.keyword, "gi");
        return str.replace(reg, str => {
          return `<span style="color:red">${str}</span>`;
        });
      });
    }
  },
  watch: {
    histroys(val) {
      setItem(LOCALSTROAGE_SEARCH_NAME, val);
    }
  },
  methods: {
    // 1 保存搜索按钮的搜索结果 keyword
    onSearch() {
      const keyword = this.keyword;
      if (keyword) {
        // this.histroys.push(keyword) // 去重
        //获取我们搜索内容
        this.addHistroy(keyword);
      }
    },
    // 2 保存关键词的搜索结果 keyword
    suggestionSearch(val) {
      let suggestions = this.suggestions;
      //  this.histroys.push(suggestions[val]) // 去重
      //  //console.log(this.histroys)
      // 我们关键词推荐的点击内容
      this.addHistroy(suggestions[val]);
    },
    addHistroy(val) {
      // ["vvv", "vvb", "vvc", "vve", "vvv"]
      //var str = ["vvv", "vvb", "vvc", "vve"]
      // vvb -> ["vvb","vvv", "vvc", "vve", "vvv"]
      // vvv-> ["vvv", "vvb", "vvc", "vve", "vvv"]
      // var test = 'vvb'
      // const idx = str.findIndex(it=>{
      //     return it === test
      // })
      // str.splice(idx,1)
      // str.unshift('vvb')
      const idx = this.histroys.findIndex(it => it === val);
      // 如果没有怎么办
      if (idx === 0) {
        return;
      }
      if (idx > -1) {
        this.histroys.splice(idx, 1);
      }
      this.histroys.unshift(val);
      // 一种访问方式
      this.$router.push({
        path: "/search/result",
        query: {
          keyword: val
        }
      });
      // this.$router.push(`/search/result?keyword=${val}`)
      // setItem(LOCALSTROAGE_SEARCH_NAME,this.histroys)
      // 第二种方案
      //  this.histroys = this.$addDifArray(this.histroys,val)
    },
    dHistory(val) {
      this.histroys.splice(val, 1);
      // setItem(LOCALSTROAGE_SEARCH_NAME,this.histroys)
    },
    useGetSuggestion() {
      // 防抖处理
      // if(this.timer){
      //     clearTimeout(this.timer)
      // }
      // this.timer = setTimeout(async()=>{
      //     if(!this.keyword){
      //         return
      //     }
      //     const res =  await getSuggestion(this.keyword)
      //     //console.log(res.data.data.options,'传智播客')
      //     this.suggestions = res.data.data.options;
      // },2*1000)
      // 节流
      /**
       * 1. 拿进去setTimeout(async()=>{。。。
       * 2. 拿进去 clearTimeout(this.timer)
       * 3 . timer =null
       */
      if (!this.timer) {
        this.timer = setTimeout(async () => {
          this.timer = null;
          if (!this.keyword) {
            return;
          }
          const res = await getSuggestion(this.keyword);
          //console.log(res.data.data.options,'传智播客')
          this.suggestions = res.data.data.options;
        }, 1 * 1000);
      }
    }
  }
};
</script>

<style scoped lang="less"></style>
